/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ozi.server.db;

import com.db4o.Db4o;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.config.Configuration;
import com.db4o.query.Query;
import com.ozi.server.utils.Configurator;
import com.ozi.server.utils.Constants;
import org.apache.log4j.Logger;

/**
 * <code>DBAccess</code> is the only method that should be used to
 * get to the database.
 * 
 * @version 0.1b
 * @author <a href="http://oziproject.org/">OZI Project</a>
 */
public class DBAccess {
    private Configurator config = Configurator.createConfig();
    private static DBAccess instance  = new DBAccess();
    private static Logger log = Logger.getLogger(DBAccess.class);
    private DBAccess() {}
    
    private ObjectContainer openDB() {
        Configuration conf = Db4o.configure();
        conf.objectClass(Zone.class).objectField("zoneName").indexed(true);
        conf.automaticShutDown(true);
        conf.lockDatabaseFile(false);
        ObjectContainer db = Db4o.openFile(Configurator.get(Constants.DB_NAME));
        return db;        
    }
    public static DBAccess getInstance() {
        return instance;
    }
    
    public void createZone(String name, String uri) {
        log.debug("Creating zone: " + name);
        ObjectContainer db = openDB();
        Zone newZone = new Zone(name, uri);
        db.set(newZone);
        db.close();
    }
    
    public Zone getZoneByName(String name) {
        log.debug("Querying zone: " + name);
        Zone zone = new Zone("","");
        ObjectContainer db = openDB();
        Query query = db.query();
        query.constrain(Zone.class);
        query.descend("zoneName").constrain(name).equal();
        ObjectSet result = query.execute();
        if (result.hasNext()) {
            zone = (Zone)result.next();
            log.debug("Found zone: " + zone.getZoneName());
        } else {
            log.debug("No zone: " + name);
        }
        return zone;
    }
    
    public void deleteZoneByName(String name) {
        ObjectContainer db = openDB();
        ObjectSet result = db.get(new Zone(name, ""));
        Zone found = (Zone)result.next();
        db.delete(found);
        db.close();
        // TODO: Recursive delete remove agents, subscribers, providers
    }
    
    public void deleteAllZones() {
        ObjectContainer db = openDB();
        ObjectSet result = db.get(Zone.class);
        while(result.hasNext()) {
            db.delete(result.next());
        }
        db.close();
        // TODO: Recursive delete remove agents, subscribers, providers
    }
}
